package net.fltx.taskmgr.controller;

import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import net.fltx.taskmgr.entity.ProcTreeTableViewEntity;
import net.fltx.taskmgr.entity.ProcessEntity;
import net.fltx.taskmgr.service.WindowsProcessService;

import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;

public class MainFormController implements Initializable {

    //进程列表
    @FXML
    private TreeTableView ttv_prc_list;
    @FXML
    private TreeTableColumn<ProcessEntity,String> ttc_pid;
    @FXML
    private TreeTableColumn<ProcessEntity,String> ttc_name;
    @FXML
    private TreeTableColumn<ProcessEntity,String> ttc_cpu;
    @FXML
    private TreeTableColumn<ProcessEntity,String> ttc_memory;
    @FXML
    private TreeTableColumn<ProcessEntity,String> ttc_path;


    @FXML
    private Button btn_close_proc;

    //进程列表管理服务
    WindowsProcessService wps;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        wps=new WindowsProcessService(ttv_prc_list,ttc_pid,ttc_name,ttc_cpu,ttc_memory,ttc_path);
        wps.init();

        ttv_prc_list.setOnMouseClicked((event -> {
            int i=ttv_prc_list.getSelectionModel().getSelectedIndex();
            System.out.println(i);
            TreeItem<ProcessEntity> modelItem = ttv_prc_list.getSelectionModel().getModelItem(i);
            System.out.println(modelItem.getValue());
        }));

    }

    /**
     * 结束进程按钮
     * @param event
     */
    @FXML
    public void btnCloseProcClick(MouseEvent event){
        int i=ttv_prc_list.getSelectionModel().getSelectedIndex();
        TreeItem<ProcessEntity> modelItem = ttv_prc_list.getSelectionModel().getModelItem(i);
        Alert conf=new Alert(Alert.AlertType.CONFIRMATION);
        conf.setHeaderText("您确定要结束进程["+modelItem.getValue().getName()+"]吗?");
        Optional<ButtonType> result = conf.showAndWait();
        if(result.isPresent() && result.get() == ButtonType.OK){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("任务管理器");
            if(wps.killProcess(modelItem.getValue())){
                alert.setHeaderText("结束["+modelItem.getValue().getName()+"]进程成功");
                modelItem.getParent().getChildren().remove(modelItem);
            }else{
                alert.setHeaderText("结束["+modelItem.getValue().getName()+"]进程失败");
            }
            alert.show();
        }
    }




}
